<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\StoreRole;
use App\Http\Resources\RoleResource;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Illuminate\Http\Request;

/**
 * Class RoleController
 * @package App\Http\Controllers\Backend
 */
class RoleController extends BackendController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $roles = Role::when($label = $request->label, function($query) use ($label) {
            $query->where('label', $label);
        })->orderBy('created_at', 'desc')->where('guard_name', 'backend')
            ->with('permissions')->paginate($request->size);
        return RoleResource::collection($roles);
    }

    /**
     * @param StoreRole $request
     * @return RoleResource
     */
    public function store(StoreRole $request)
    {
        $role = Role::create([
            'guard_name' => 'backend',
            'name' => md5(uniqid(microtime(true),true)),
            'label' => $request->label,
            'description' => $request->description
        ]);
        $permissions = Permission::whereIn('id',$request->permissions)->get();
        $role->syncPermissions($permissions);
        return new RoleResource($role);
    }

    /**
     * @param Role $role
     * @return RoleResource
     */
    public function update(Role $role)
    {
        $role->label = \request()->label;
        $role->description = \request()->description;
        $permissions = Permission::whereIn('id',\request()->permissions)->get();
        $role->syncPermissions($permissions);
        $role->save();
        return new RoleResource($role);
    }

    /**
     * @param Role $role
     * @return RoleResource
     * @throws \Exception
     */
    public function destroy(Role $role)
    {
        $role->delete();
        return new RoleResource($role);
    }
}
